// src/components/timeline/Track.tsx
import React, { useState, useRef, useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { DndContext, DragEndEvent, DragMoveEvent, PointerSensor, useSensor, useSensors } from '@dnd-kit/core';
import { restrictToHorizontalAxis } from '@dnd-kit/modifiers';
import Segment, { SegmentData, SegmentType } from './Segment';
import AddVideoClipModal from '@/components/project/AddVideoClipModal';
import AddAudioClipModal from '@/components/project/AddAudioClipModal';
import AddTextClipModal from '@/components/project/AddTextClipModal';
import TransitionModal from './TransitionModal';
import './TransitionButton.css';
import { ITrack, ITrackSegment } from '@/store/types/track';
import { RootState, store } from '@/store';
import { selectTracks, updateTracks } from '@/store/draftsSlice';
import { setSelectedSegment, selectSelectedSegment, SelectedSegmentInfo } from '@/store/selectedSegmentSlice';
import { eventBus, createDebounce } from '@/utils';
import { updateSegment, updateSegmentVideoOperations } from '@/services/project';
import { message } from 'antd';
interface TrackProps {
    track: ITrack;
    pixelsPerSecond: number;
    onClipDragStart: () => void;
    isSelected?: boolean;
    onClick?: (track: ITrack) => void;
    onContextMenu?: (track: ITrack, event: React.MouseEvent) => void;
}
// 轨道的层级枚举
enum TrackLevel {
    TEXT = 9999,
    IMAGE = 5000,
    VIDEO = 2000,
    AUDIO = 1000,
}

const Track: React.FC<TrackProps> = ({ track, pixelsPerSecond, onClipDragStart, isSelected = false, onClick, onContextMenu }) => {
    // 获取当前草稿ID
    const draft = useSelector((state: RootState) => state.drafts);
    const currentDraftId = useSelector((state: RootState) => state.drafts.draftId);
    const allTracks = selectTracks({ draft: draft }) || [];
    console.log('全部的轨道', allTracks);
    const dispatch = useDispatch();

    // 计算当前轨道的render_index
    const currentTrackType = () => {
        const type = allTracks.find((t: ITrack) => t.id === track.id)?.type;
        switch (type) {
            case 'text':
                return TrackLevel.TEXT;
            case 'video':
                return TrackLevel.VIDEO;
            case 'audio':
                return TrackLevel.AUDIO;
            default: {
                console.warn('当前轨道的类型', type);
                return TrackLevel.VIDEO;
            }
        }
    };
    const renderIndex = currentTrackType();
    // 模态框状态
    const [isVideoModalVisible, setIsVideoModalVisible] = useState(false);
    const [isAudioModalVisible, setIsAudioModalVisible] = useState(false);
    const [isTextModalVisible, setIsTextModalVisible] = useState(false);
    const [isTransitionModalVisible, setIsTransitionModalVisible] = useState(false);
    const [transitionTargetSegmentId, setTransitionTargetSegmentId] = useState<string>('');
    // 配置拖拽传感器，提高响应性
    const sensors = useSensors(
        useSensor(PointerSensor, {
            activationConstraint: {
                distance: 1, // 降低激活距离，提高响应性
            },
        })
    );
    // 处理拖拽开始
    const handleDragStart = (event: any) => {
        const { active } = event;
        const activeId = active.id as string;

        onClipDragStart();

        // 记录初始状态 - 将ITrackSegment转换为SegmentData进行操作
        if (track.segments && track.segments.length > 0) {
            const convertedSegments = track.segments.map((segment) => convertToSegmentData(segment)).filter((segment) => segment !== null) as SegmentData[];
            dragStartSegmentsRef.current = [...convertedSegments];
            dragStartActiveIdRef.current = activeId;
        }
    };

    // 辅助函数：更新轨道中的特定片段
    const updateTrackSegment = (segmentId: string, updates: Partial<ITrackSegment>) => {
        const updatedTracks = allTracks.map((t: ITrack) => {
            if (t.id === track.id) {
                return {
                    ...t,
                    segments: t.segments.map((segment: ITrackSegment) => {
                        if (segment.id === segmentId) {
                            return { ...segment, ...updates };
                        }
                        return segment;
                    }),
                };
            }
            return t;
        });
        dispatch(updateTracks(updatedTracks));
    };

    // 更新数据库中的片段信息
    const updateSegmentInDatabase = async (segmentId: string) => {
        try {
            // 从Redux store获取最新的轨道和片段数据
            const currentState = store.getState() as RootState;
            const latestDraft = currentState.drafts;
            const latestTracks = selectTracks({ draft: latestDraft }) || [];

            // 找到当前轨道
            const currentTrack = latestTracks.find((t: ITrack) => t.id === track.id);
            if (!currentTrack) {
                return;
            }

            // 找到要更新的片段
            const updatedSegment = currentTrack.segments?.find((s: ITrackSegment) => s.id === segmentId);
            if (!updatedSegment) {
                return;
            }
            // 构造更新数据
            const updateData: any = {
                type: track.type,
                start: updatedSegment.target_timerange.start,
                duration: updatedSegment.target_timerange.duration,
                segment_config: {}, // 传递空对象
            };

            // 如果是视频或音频类型，需要传递 material_id
            if ((track.type === 'video' || track.type === 'audio') && updatedSegment.material_id) {
                updateData.material_id = updatedSegment.material_id;
            }
            // 调用更新接口
            await updateSegment(currentDraftId as string, track.id, segmentId, updateData);
            message.success('更新片段成功');
            // 发送事件总线通知，获取最新草稿数据
            eventBus.emit('draft:updated', { draftId: currentDraftId });
        } catch (error) {
            console.error('更新片段失败:', error);
        }
    };

    // 创建防抖实例，800毫秒延迟，1秒内取消重复调用
    const debouncedUpdateSegment = createDebounce(updateSegmentInDatabase, {
        delay: 800,
        cancelThreshold: 1000,
    });

    // 处理拖拽移动 - 实时响应
    const handleDragMove = (event: DragMoveEvent) => {
        const { active, delta } = event;
        if (delta.x !== 0) {
            const activeId = active.id as string;
            const deltaTime = delta.x / pixelsPerSecond;
            if (activeId.includes('-left-resize')) {
                const segmentId = activeId.replace('-left-resize', '');
                const originalSegment = dragStartSegmentsRef.current.find((s) => s.id === segmentId);
                if (originalSegment) {
                    const newStart = Math.max(0, originalSegment.start + deltaTime);
                    const newDuration = Math.max(0.1, originalSegment.duration - deltaTime);
                    updateTrackSegment(segmentId, {
                        target_timerange: {
                            start: newStart * 1000000, // 转换回毫秒
                            duration: newDuration * 1000000,
                        },
                    });
                }
            } else if (activeId.includes('-right-resize')) {
                const segmentId = activeId.replace('-right-resize', '');
                const originalSegment = dragStartSegmentsRef.current.find((s) => s.id === segmentId);

                if (originalSegment) {
                    const newDuration = Math.max(0.1, originalSegment.duration + deltaTime);
                    updateTrackSegment(segmentId, {
                        target_timerange: {
                            ...track.segments.find((s) => s.id === segmentId)?.target_timerange,
                            duration: newDuration * 1000000, // 转换回毫秒
                        },
                    });
                }
            }
        }
    };

    // 检测片段时间重合的函数（基于SegmentData）
    const checkSegmentOverlap = (targetSegment: SegmentData, allSegments: SegmentData[]): boolean => {
        const targetStart = targetSegment.start;
        const targetEnd = targetSegment.start + targetSegment.duration;

        return allSegments.some((segment) => {
            if (segment.id === targetSegment.id) return false; // 跳过自己

            const segmentStart = segment.start;
            const segmentEnd = segment.start + segment.duration;

            // 检测时间重合：目标片段的开始时间在其他片段范围内，或结束时间在其他片段范围内，或完全包含其他片段
            return targetStart < segmentEnd && targetEnd > segmentStart;
        });
    };

    // 处理拖拽结束
    const handleDragEnd = (event: DragEndEvent) => {
        const { active, delta } = event;

        if (delta.x !== 0) {
            const activeId = active.id as string;
            const deltaTime = delta.x / pixelsPerSecond;

            // 获取当前轨道的所有片段（转换为SegmentData进行重合检测）
            const currentSegments = track.segments.map((segment) => convertToSegmentData(segment)).filter((segment) => segment !== null) as SegmentData[];

            // 检查是否是resize操作
            if (activeId.includes('-left-resize')) {
                // 左侧resize：检测重合并可能弹回
                const segmentId = activeId.replace('-left-resize', '');
                const originalSegment = dragStartSegmentsRef.current.find((s) => s.id === segmentId);

                if (originalSegment) {
                    const newStart = Math.max(0, originalSegment.start + deltaTime);
                    const newDuration = Math.max(0.1, originalSegment.duration - deltaTime);
                    const testSegment = { ...originalSegment, start: newStart, duration: newDuration };

                    if (checkSegmentOverlap(testSegment, currentSegments)) {
                        // 发生重合，弹回到原始状态
                        updateTrackSegment(segmentId, {
                            target_timerange: {
                                start: originalSegment.start * 1000000, // 转换回毫秒
                                duration: newDuration * 1000000,
                            },
                        });
                        // 防抖调用更新数据库接口
                        debouncedUpdateSegment.execute(segmentId);
                    } else {
                        // 防抖调用更新数据库接口
                        debouncedUpdateSegment.execute(segmentId);
                    }
                }
            } else if (activeId.includes('-right-resize')) {
                // 右侧resize：检测重合并可能弹回
                const segmentId = activeId.replace('-right-resize', '');
                const originalSegment = dragStartSegmentsRef.current.find((s) => s.id === segmentId);

                if (originalSegment) {
                    const newDuration = Math.max(0.1, originalSegment.duration + deltaTime);
                    const testSegment = { ...originalSegment, duration: newDuration };

                    if (checkSegmentOverlap(testSegment, currentSegments)) {
                        // 发生重合，弹回到原始状态
                        const originalTrackSegment = track.segments.find((s) => s.id === segmentId);
                        if (originalTrackSegment) {
                            updateTrackSegment(segmentId, {
                                target_timerange: {
                                    ...originalTrackSegment.target_timerange,
                                    duration: newDuration * 1000000, // 转换回毫秒
                                },
                            });
                        }
                        // 防抖调用更新数据库接口
                        debouncedUpdateSegment.execute(segmentId);
                    } else {
                        // 防抖调用更新数据库接口
                        debouncedUpdateSegment.execute(segmentId);
                    }
                }
            } else {
                // 普通拖拽：检测重合并可能弹回
                const segmentId = activeId;
                const originalSegment = dragStartSegmentsRef.current.find((s) => s.id === segmentId);

                if (originalSegment) {
                    const newStart = Math.max(0, originalSegment.start + deltaTime);
                    const testSegment = { ...originalSegment, start: newStart };

                    if (checkSegmentOverlap(testSegment, currentSegments)) {
                        // 发生重合，弹回到原始状态
                        updateTrackSegment(segmentId, {
                            target_timerange: {
                                start: originalSegment.start * 1000000, // 转换回毫秒
                                duration: originalSegment.duration * 1000000,
                            },
                        });
                        // 防抖调用更新数据库接口
                        debouncedUpdateSegment.execute(segmentId);
                    } else {
                        // 无重合，正常更新位置
                        updateTrackSegment(segmentId, {
                            target_timerange: {
                                start: newStart * 1000000,
                                duration: originalSegment.duration * 1000000,
                            },
                        });
                        // 防抖调用更新数据库接口
                        debouncedUpdateSegment.execute(segmentId);
                    }
                }
            }
        }
    };
    // 使用Redux全局状态获取选中的片段
    const selectedSegment = useSelector(selectSelectedSegment);
    // 存储拖拽开始时的原始segment数据
    const dragStartSegmentsRef = useRef<SegmentData[]>([]);
    const dragStartActiveIdRef = useRef<string | null>(null);
    // 将ITrackSegment转换为SegmentData
    const convertToSegmentData = (segment: ITrackSegment): SegmentData | null => {
        try {
            // 映射轨道类型到片段类型
            const mapTrackTypeToSegmentType = (trackType: ITrack['type']): SegmentType => {
                switch (trackType) {
                    case 'video':
                        return 'video';
                    case 'audio':
                        return 'audio';
                    case 'text':
                        return 'text';
                    default:
                        return 'video'; // 默认类型
                }
            };

            // 生成片段名称
            const generateSegmentName = (trackType: ITrack['type'], segmentId: string): string => {
                const typeNames = {
                    video: '视频片段',
                    audio: '音频片段',
                    text: '文本片段',
                    sticker: '贴纸片段',
                    background: '背景片段',
                    effect: '特效片段',
                    filter: '滤镜片段',
                    adjust: '调整片段',
                };
                return `${typeNames[trackType] || '片段'}_${segmentId.slice(-6)}`;
            };
            let content = null;
            if (track.type === 'text') {
                content = JSON.parse(segment.material_info?.original_properties.content).text;
            }
            const segmentData: SegmentData = {
                id: segment.id,
                type: mapTrackTypeToSegmentType(track.type),
                name: generateSegmentName(track.type, segment.id),
                duration: segment.target_timerange.duration / 1000000, // 微妙转换为秒
                start: segment.target_timerange.start / 1000000, // 微妙转换为秒
                clipSettings: segment.clip,
                volume: segment.volume,
                speed: segment.speed,
                visible: segment.visible,
                // 可选字段根据需要设置
                content: content, // 文本内容，如果是文本类型可以从其他地方获取
                src: segment.material_info.public_url, // 媒体源地址，需要根据 material_id 获取
                thumbnail: undefined, // 缩略图地址，需要根据 material_id 获取
                currentTrackIndex: renderIndex,
            };
            return segmentData;
        } catch (error) {
            console.error('转换ITrackSegment到SegmentData失败:', error, segment);
            return null;
        }
    };

    // 根据轨道类型获取图标
    const getIcon = (type: ITrack['type']) => {
        // 只有三种类型 贴纸也属于视频类型 只不过是上传图片
        switch (type) {
            case 'text':
                return '📝';
            case 'video':
                return '🎥';
            case 'audio':
                return '🎵';
            default:
                return '❓';
        }
    };

    // 处理添加素材按钮点击
    const handleAddItem = (e: React.MouseEvent) => {
        e.stopPropagation(); // 阻止事件冒泡到轨道容器
        // 根据轨道类型显示不同的模态框
        switch (track.type) {
            case 'video':
            case 'sticker': // 图片类型也使用视频组件
                setIsVideoModalVisible(true);
                break;
            case 'audio':
                setIsAudioModalVisible(true);
                break;
            case 'text':
                setIsTextModalVisible(true);
                break;
            default:
                console.warn('未支持的轨道类型:', track.type);
        }
    };

    // 存储当前片段的表单数据
    const [currentFormData, setCurrentFormData] = useState<any>(null);

    // 监听表单数据变化事件
    useEffect(() => {
        const unsubscribeFormDataChanged = (eventBus as any).on('form:data:changed', (data: any) => {
            setCurrentFormData(data);
        });

        return () => {
            unsubscribeFormDataChanged();
        };
    }, []);

    // 保存当前选中片段的修改
    const saveCurrentSegmentChanges = async () => {
        if (!selectedSegment || !currentFormData) return;

        try {
            if (currentFormData.formType === 'video') {
                // 保存视频配置
                const updateData = {
                    type: 'video',
                    material_id: currentFormData.formData.material_id,
                    segment_config: {
                        volume: currentFormData.formData.volume,
                        clip: currentFormData.formData.clip,
                    },
                };
                await updateSegment(currentFormData.formData.draftId, currentFormData.formData.trackId, currentFormData.formData.id, updateData);
            } else if (currentFormData.formType === 'text') {
                // 保存文本配置
                const updateData = {
                    type: 'text',
                    start: currentFormData.formData.start,
                    duration: currentFormData.formData.duration,
                    segment_config: {
                        text: currentFormData.formData.textContent?.text || '',
                        clip: currentFormData.formData.clip,
                        styles: currentFormData.formData.textContent?.styles || [],
                    },
                };
                await updateSegment(currentFormData.formData.draftId, currentFormData.formData.trackId, currentFormData.formData.id, updateData);
            } else if (currentFormData.formType === 'base') {
                // 保存基础配置（特效等）
                await updateSegmentVideoOperations(currentFormData.formData.draftId, currentFormData.formData.trackId, currentFormData.formData.id, currentFormData.formData.operations);
            }

            // 清空当前表单数据
            setCurrentFormData(null);
        } catch (error) {
            console.error('保存片段修改失败:', error);
        }
    };

    // 处理片段选中
    const handleSegmentSelect = (segment: SegmentData) => {
        const currentSelectedId = selectedSegment?.id;
        const newSelectedId = segment.id === currentSelectedId ? null : segment.id;
        // 发送事件总线更新
        // 如果当前没有选中片段，或者选中的是不同片段，才需要保存
        if (currentSelectedId && newSelectedId && currentSelectedId !== newSelectedId) {
            saveCurrentSegmentChanges();
        } else if (currentSelectedId && !newSelectedId) {
            saveCurrentSegmentChanges();
        }
        eventBus.emit('draft:updated', { draftId: currentDraftId });
        // 在事件总线更新后，获取最新的草稿信息并存储选中片段
        setTimeout(() => {
            if (newSelectedId) {
                // 获取最新的tracks数据
                const currentState = store.getState() as RootState;
                const latestDraft = currentState.drafts;
                const latestTracks = selectTracks({ draft: latestDraft }) || [];
                // 根据片段ID过滤出选中的片段信息
                let selectedSegmentInfo: SelectedSegmentInfo | null = null;
                for (const track of latestTracks) {
                    if (track.segments) {
                        const foundSegment = track.segments.find((seg: ITrackSegment) => seg.id === newSelectedId);
                        if (foundSegment) {
                            // 直接存储ITrackSegment数据，并添加轨道类型信息
                            selectedSegmentInfo = {
                                id: foundSegment.id,
                                start: foundSegment.target_timerange.start, // 微妙转换为秒
                                duration: foundSegment.target_timerange.duration, // 微妙转换为秒
                                type: track.type,
                                trackId: track.id,
                                draftId: currentDraftId as string,
                                clip: foundSegment.clip,
                                volume: foundSegment.volume || null,
                                material_id: foundSegment.material_id || '',
                            };
                            break;
                        }
                    }
                }
                // 存储到Redux store中
                dispatch(setSelectedSegment(selectedSegmentInfo));
            } else {
                // 如果取消选中，清除store中的数据
                dispatch(setSelectedSegment(null));
            }
        }, 100); // 给事件总线一些时间来更新数据
    };
    // 处理视频片段模态框取消
    const handleVideoModalCancel = () => {
        setIsVideoModalVisible(false);
    };

    // 处理音频模态框取消
    const handleAudioModalCancel = () => {
        setIsAudioModalVisible(false);
    };

    const handleTextModalCancel = () => {
        setIsTextModalVisible(false);
    };

    // 获取当前草稿的转场素材列表
    const currentDraft = useSelector((state: RootState) => state.drafts.scriptData);
    const transitions = currentDraft?.materials?.transitions || [];
    const transitionIds = transitions.map((t: any) => t.id);

    // 检查片段是否已有转场
    const hasTransition = (segment: ITrackSegment): boolean => {
        if (!segment.extra_material_refs || segment.extra_material_refs.length === 0) {
            return false;
        }
        
        if (transitions.length === 0) {
            return false;
        }
        
        // 检查片段的extra_material_refs中是否包含转场素材ID
        return segment.extra_material_refs.some(refId => transitionIds.includes(refId));
    };

    // 处理转场按钮点击
    const handleTransitionClick = (segmentId: string) => {
        setTransitionTargetSegmentId(segmentId);
        setIsTransitionModalVisible(true);
    };

    // 处理转场模态框取消
    const handleTransitionModalCancel = () => {
        setIsTransitionModalVisible(false);
        setTransitionTargetSegmentId('');
    };

    // 处理转场添加成功
    const handleTransitionSuccess = () => {
        setIsTransitionModalVisible(false);
        setTransitionTargetSegmentId('');
        // 刷新草稿数据
        eventBus.emit('draft:updated', { draftId: currentDraftId });
    };

    return (
        <div
            className="track-container"
            onClick={() => onClick?.(track)}
            onContextMenu={(e) => {
                e.preventDefault();
                onContextMenu?.(track, e);
            }}
            style={{
                width: '100%',
                display: 'flex',
                marginBottom: '2px',
                backgroundColor: '#2a2a2a',
                borderRadius: '4px',
                overflow: 'hidden',
                height: '45px',
                border: isSelected ? '2px solid #ffffff' : '2px solid transparent',
                cursor: 'pointer',
                transition: 'border-color 0.2s ease',
            }}
        >
            {/* 左侧轨道头部 - 30% 宽度 */}
            <div
                className="track-header"
                style={{
                    height: '45px',
                    width: '200px',
                    minWidth: '200px',
                    borderRight: '1px solid #444',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'space-between',
                    padding: '0 12px',
                    boxSizing: 'border-box',
                    backgroundColor: '#252525',
                    flexShrink: 0,
                }}
            >
                <div style={{ display: 'flex', alignItems: 'center', gap: '8px', flex: 1, minWidth: 0 }}>
                    <span className="track-icon" style={{ fontSize: '16px', flexShrink: 0 }}>
                        {getIcon(track.type)}
                    </span>
                    <span
                        className="track-title"
                        style={{
                            fontSize: '13px',
                            color: '#f0f0f0',
                            fontWeight: '500',
                            whiteSpace: 'nowrap',
                            overflow: 'hidden',
                            textOverflow: 'ellipsis',
                            flex: 1,
                            minWidth: 0,
                        }}
                    >
                        {track.name}
                    </span>
                </div>

                {/* 轨道控制按钮 */}
                <div className="track-controls" style={{ display: 'flex', gap: '4px', flexShrink: 0 }}>
                    <button
                        className="add-item-btn"
                        onClick={handleAddItem}
                        style={{
                            background: 'none',
                            border: 'none',
                            color: '#52c41a',
                            cursor: 'pointer',
                            fontSize: '14px',
                            padding: '4px',
                            borderRadius: '2px',
                            transition: 'background-color 0.2s ease',
                        }}
                        onMouseEnter={(e) => {
                            e.currentTarget.style.backgroundColor = 'rgba(82, 196, 26, 0.1)';
                        }}
                        onMouseLeave={(e) => {
                            e.currentTarget.style.backgroundColor = 'transparent';
                        }}
                    >
                        ➕
                    </button>
                </div>
            </div>

            {/* 右侧轨道内容区域 - 固定3000像素宽度 */}
            <div
                className={`track-content ${track.type}`}
                style={{
                    height: '45px',
                    width: '3000px',
                    position: 'relative',
                    overflow: 'hidden',
                    backgroundColor: '#1a1a1a',
                    flexShrink: 0,
                }}
            >
                <DndContext sensors={sensors} onDragStart={handleDragStart} onDragMove={handleDragMove} onDragEnd={handleDragEnd} modifiers={[restrictToHorizontalAxis]}>
                    {/* 渲染片段和转场按钮 */}
                    {track.segments &&
                        track.segments.length > 0 &&
                        track.segments.map((segment: ITrackSegment, index: number) => {
                            const segmentData = convertToSegmentData(segment);
                            if (!segmentData) return null;

                            return (
                                <React.Fragment key={segment.id}>
                                    {/* 渲染片段 */}
                                    <Segment
                                        segment={segmentData}
                                        pixelsPerSecond={pixelsPerSecond}
                                        isSelected={selectedSegment?.id === segment.id}
                                        onSelect={handleSegmentSelect}
                                        showPreview={true}
                                        trackId={track.id}
                                        draftId={currentDraftId as string}
                                    />
                                    
                                    {/* 在每两个片段之间渲染转场按钮 - 只有视频轨道显示 */}
                                    {index < track.segments.length - 1 && track.type === 'video' && (
                                        <div
                                            key={`transition-${segment.id}`}
                                            className="transition-button-container"
                                            style={{
                                                left: `${(segmentData.start + segmentData.duration) * pixelsPerSecond - 8}px`,
                                            }}
                                        >
                                            <button
                                                className={`transition-button ${hasTransition(segment) ? 'has-transition' : 'no-transition'}`}
                                                onClick={(e) => {
                                                    e.stopPropagation();
                                                    handleTransitionClick(segment.id);
                                                }}
                                                title={hasTransition(segment) ? "已添加转场" : "添加转场"}
                                            >
                                                <span className="transition-icon">&lt;&gt;</span>
                                            </button>
                                        </div>
                                    )}
                                </React.Fragment>
                            );
                        })}
                </DndContext>
            </div>
            {/* 根据轨道类型渲染不同的模态框组件 */}
            {(() => {
                switch (track.type) {
                    case 'video':
                    case 'sticker': // 图片类型也使用视频组件
                        return <AddVideoClipModal visible={isVideoModalVisible} trackId={track.id} draftId={currentDraftId as string} trackType={'video'} renderIndex={renderIndex} onCancel={handleVideoModalCancel} />;
                    case 'audio':
                        return <AddAudioClipModal visible={isAudioModalVisible} trackId={track.id} draftId={currentDraftId as string} renderIndex={renderIndex} onCancel={handleAudioModalCancel} />;
                    case 'text':
                        return <AddTextClipModal visible={isTextModalVisible} trackId={track.id} draftId={currentDraftId as string} renderIndex={renderIndex} onCancel={handleTextModalCancel} />;
                    default:
                        return <div>轨道渲染错误！</div>;
                }
            })()}
            
            {/* 转场模态框 */}
            <TransitionModal
                visible={isTransitionModalVisible}
                onCancel={handleTransitionModalCancel}
                onSuccess={handleTransitionSuccess}
                draftId={currentDraftId as string}
                trackId={track.id}
                segmentId={transitionTargetSegmentId}
            />
        </div>
    );
};

export default Track;
